<?php

namespace app\admin\controller;

use app\admin\common\Common;
use app\admin\common\Upload;
use app\admin\model\AppModel;
use app\admin\validate\AppValidate;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Request;

class App extends LoginThere
{

    public function index(){
        try {
            $listApp = Db::name('app')->paginate(10);
            $page = $listApp->render();
            return $this->fetch('/app/index', ['list' => $listApp, 'page' => $page]);
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }

    }

    public function queryapp($appid){
        try {
            $listApp = Db::name('app')->where('appid', $appid)->find();
        } catch (DataNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (ModelNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }
        return $this->fetch('app/queryapp')->assign('app',$listApp);
    }


    public function updateapp(Request $request){
        $data = $request->post();
        $validate = new AppValidate();
        if (!$validate->scene('updateapp')->check($data)) {
            return Common::result(400,$validate->getError());
        }
        return AppModel::updateapp($data);
    }


    public function addapp(Request  $request){
        $data = $request->post();
        $validate = new AppValidate();
        if (!$validate->scene('addapp')->check($data)){
            return Common::result(400,$validate->getError());
        }
        return AppModel::addapp($data);
    }


    public function delapp(Request  $request){
        $data = $request->post();
        return AppModel::delapp($data);
    }

    public function upload(){
        $upload = new Upload();
        $file = $upload->uploadDetail('file');
        Db::name('upload')->insert($file);
        return Common::result(200,"上传成功",array($file));
    }

    public function searchapp(Request $request){
        if (!empty($data['appname'])){
            return Common::result(400,"请输入完整");
        }
        $data = $request->post();
        return AppModel::searchapp($data);
    }

}